#include "NControllerManager.h"
#include "NeroCore\NMemoryManager.h"

using namespace Game;

NControllerManager* NControllerManager::sInstance = NULL;

NControllerManager::NControllerManager(void)
	:mControllers(NULL),
	 mCheckControllers(true),
	 mNumberOfControllers(0)
{
	Initialize();
}

NControllerManager::~NControllerManager(void)
{
	Deinitialize();
}

void NControllerManager::Initialize()
{
	mControllers = MY_NEW(Memory::HID_Engine,"Controller Array")NController*[4];
}

void NControllerManager::Deinitialize()
{
	for(int i = 0; i < mNumberOfControllers; i++)
	{
		MY_DELETE(mControllers[i]);
	}

	if(mControllers != NULL)
	{
		MY_DELETE_ARRAY(mControllers);
	}
}

void NControllerManager::Update(float gameTime)
{
	if(mCheckControllers)
	{
		mCheckControllers = false;
		for (int i = 0; i < 1; i++)
		{
			if(mControllers[i] != NULL)
			{
				mControllers[i]->Initialize();
			}
		}
	}

	for (int i = 0; i < 1; i++)
	{
		if(mControllers[i] != NULL)
		{
			mControllers[i]->Update(gameTime);
		}
	}
}

void NControllerManager::AddController(NController* controller)
{
	mControllers[0] = controller;

	mNumberOfControllers++;
}

void NControllerManager::RemoveController(NController*)
{
	mNumberOfControllers--;
}

NController* NControllerManager::GetController(int index)
{
	if(index < mNumberOfControllers-1 || index > mNumberOfControllers)
	{
		return NULL;
	}

	return mControllers[index];
}

void NControllerManager::CreateInstance()
{
	if(sInstance == NULL)
	{
		sInstance = MY_NEW(Memory::HID_Engine,"NControllerManager") NControllerManager();
	}
}

void NControllerManager::DestroyInstance()
{
	if(sInstance != NULL)
	{
		MY_DELETE(sInstance);
	}
}

NControllerManager* NControllerManager::GetInstance()
{
	return sInstance;
}